package org.spiderflow.common.control;

import org.spiderflow.common.redis.userinfo.RedisUserInfoUtil;
import org.spiderflow.common.utils.CommonUtils;
import org.spiderflow.config.ResponseResult;
import org.spiderflow.config.RestResultGenerator;
import org.spiderflow.file.bean.File;
import org.spiderflow.file.service.FileService;
import org.spiderflow.users.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author: tjs
 * @Date: 2019/5/19 21:56
 * @Desc:
 */
@RestController
@RequestMapping("/common")
public class CommonControl {

    @Autowired
    FileService fileService;
    @Autowired
    RedisUserInfoUtil redisUserInfoUtil;


    private static String UPLOAD_PATH = "File/image/upload";

    /**
     * 实现文件上传
     */
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<File> fileUpload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            return RestResultGenerator.genErrorResult("未上传图片！");
        }
        org.spiderflow.file.bean.File fileData = new org.spiderflow.file.bean.File();
        String fileName = CommonUtils.getFileName(1, file.getOriginalFilename());
        System.out.println(">>>>开始加图片了" + fileName);

        try {

            InputStream inputStream = file.getInputStream();
            Path directory = Paths.get(UPLOAD_PATH);

            System.out.println(">>>>开始加图片了" + directory.toString());
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);

            }
            long copy = Files.copy(inputStream, directory.resolve(fileName));

//                file.transferTo(dest); //保存文件

            fileData.setFileName(fileName);
//                fileData.setFileUrl("/static/images/" + fileName);
            fileData.setFileUrl(UPLOAD_PATH + "/" + fileName);
            fileData.setFileType(1);

            //绑定登录信息
            Users userInfo = redisUserInfoUtil.getUserByKey();
            fileData.setCreateId(userInfo.getUserId());
            fileData.setCreateName(userInfo.getUserPhone());

            fileService.save(fileData);
//                return "true";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//                return "false";
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//                return "false";
        }

        return RestResultGenerator.genResult(fileData, "上传成功！");
    }


}
